<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="呼叫名单" required v-if="!formData.id">
        <div class="call-box">
          <div class="call-select" @click="selectCallPhone" v-if="selectCallName">
            {{ selectCallName }}
          </div>
          <div class="call-holder" @click="selectCallPhone" v-else> 请选择呼叫名单</div>
          <div
            class="icon-box"
            @click="selectCallPhone"
            style="border-right: 1px solid #dadada; border-left: 1px solid #dadada"
          >
            <el-icon size="16">
              <EditPen />
            </el-icon>
          </div>
          <div class="icon-box" @click="addCall">
            <el-icon size="16">
              <Plus />
            </el-icon>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select
          v-model="formData.type"
          :disabled="taskId ? true : false"
          placeholder="请选择任务类型"
          style="width: 100%"
        >
          <el-option label="AI外呼" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="机器人流程" prop="ivrFlowId">
        <el-select v-model="formData.ivrFlowId" placeholder="请选择机器人流程" class="w-100%">
          <el-option v-for="item in ivrOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="TTS音色" prop="timbreId">
        <el-select v-model="formData.timbreId" placeholder="请选择TTS音色" class="w-100%">
          <el-option
            v-for="item in ttsTimbreOption"
            :key="item.id"
            :label="item.timbreName"
            :value="item.timbreId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="外呼号码" prop="outnumberIdList">
        <el-select v-model="formData.outnumberIdList" multiple style="width: 100%">
          <el-option
            v-for="item in outNumberList"
            :key="item.id"
            :value="item.id"
            :label="item.displayNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联大模型质检" prop="aiQualityTestingId">
        <el-select-v2
          filterable
          v-model="formData.aiQualityTestingId"
          placeholder="请选择大模型质检"
          class="w-1/1"
          :options="qualityOption"
          :props="{
            value: 'id',
            label: 'name'
          }"
        >
        </el-select-v2>
      </el-form-item>
      <el-form-item label="最高并发">
        <el-input-number v-model="formData.maxNum" :min="1" />
      </el-form-item>
      <!-- <el-form-item label="自动重呼">
        <el-radio-group v-model="formData.autoRecall">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <div v-if="formData.autoRecall == 0">
        <el-form-item label="重呼次数(1-4)">
          <el-input-number v-model="formData.recallTime" :min="1" :max="4" />
        </el-form-item>
        <el-form-item label="重呼间隔(秒)">
          <el-input-number v-model="formData.dialInterval" :min="1" />
        </el-form-item>
      </div>
      <el-form-item label="有效时段1">
        <div class="week-box">
          <div class="time-box">
            <el-time-picker
              clearable
              v-model="formData.startTime1"
              value-format="HH:mm:ss"
              placeholder="请选择时间"
            >
            </el-time-picker>
            <el-time-picker
              clearable
              v-model="formData.endTime1"
              value-format="HH:mm:ss"
              placeholder="请选择时间"
            >
            </el-time-picker>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="有效时段2">
        <div class="week-box">
          <div class="time-box">
            <el-time-picker
              v-model="formData.startTime2"
              value-format="HH:mm:ss"
              clearable
              placeholder="请选择时间"
            >
            </el-time-picker>
            <el-time-picker
              clearable
              v-model="formData.endTime2"
              value-format="HH:mm:ss"
              placeholder="请选择时间"
            >
            </el-time-picker>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="有效时段3">
        <div class="week-box">
          <div class="time-box">
            <el-time-picker
              v-model="formData.startTime3"
              value-format="HH:mm:ss"
              clearable
              placeholder="请选择时间"
            >
            </el-time-picker>
            <el-time-picker
              clearable
              v-model="formData.endTime3"
              value-format="HH:mm:ss"
              placeholder="请选择时间"
            >
            </el-time-picker>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <CallSelects ref="callRefs" @changeCalle="changeCalle" />
  <VoiceSelects ref="voiceRefs" @changeVoice="changeVoice" />
  <callListForm ref="callListRefs" />
  <VoiceForm ref="voiceListRefs" />
</template>
<script setup lang="ts">
import { EditPen, Plus } from '@element-plus/icons-vue'
import * as TaskApi from '@/api/call/task'
import * as AgentApi from '@/api/call/agent'
import * as CmOutnumberApi from '@/api/call/cmoutnumber'
import CallSelects from './call.vue'
import callListForm from './callList/callListForm.vue'
import VoiceForm from './voiceFile/voiceForm.vue'
import VoiceSelects from './voice.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getIvrGroupList } from '@/api/call/ivr'
import { getQualitySimpleList } from '@/api/call/model_quality/index'

const outNumberList = ref([]) //号码列表
const selectCallName = ref(null)
const selectVoiceName = ref(null)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const ttsTimbreOption = ref([])
const ivrOptions = ref([])
const groupOptions = ref([]) //班组列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改  detail-详情
const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  audioFile: undefined,
  outnumberIdList: [],
  aiQualityTestingId: undefined,
  maxNum: 1,
  autoRecall: 1,
  recallTime: 1,
  dialInterval: 1,

  callTaskCalleeListId: undefined, //呼叫名单id

  key1: undefined,
  action1: undefined,

  key2: undefined,
  action2: undefined,

  key3: undefined,
  action3: undefined,

  startTime1: undefined,
  endTime1: undefined,

  startTime2: undefined,
  endTime2: undefined,

  startTime3: undefined,
  endTime3: undefined,

  ivrFlowId: ''
})
const formRules = reactive({
  name: [
    {
      required: true,
      message: '任务名称不能为空',
      trigger: 'blur'
    }
  ],
  timbreId: [
    {
      required: true,
      message: 'TTS音色不能为空',
      trigger: 'change'
    }
  ],
  outnumberIdList: [
    {
      required: true,
      message: '外呼号码不能为空',
      trigger: 'change'
    }
  ],
  aiQualityTestingId: [
    {
      required: true,
      message: '关联大模型质检不能为空',
      trigger: 'change'
    }
  ],
  type: [
    {
      required: true,
      message: '任务类型不能为空',
      trigger: 'change'
    }
  ],
  key1: [
    {
      required: true,
      message: '请选择按键',
      trigger: 'change'
    }
  ],
  action1: [
    {
      required: true,
      message: '请选择按键执行动作',
      trigger: 'change'
    }
  ],
  weekDay: [
    {
      required: true,
      message: '请选择有效时段',
      trigger: 'change'
    }
  ],
  ivrFlowId: [
    {
      required: true,
      message: '请选择机器人流程',
      trigger: 'change'
    }
  ]
})
const callRefs = ref(null)
/*选择通话名单*/
const selectCallPhone = () => {
  callRefs.value.open()
}
const voiceRefs = ref(null)
/*选择语音文件*/
const selectVoiceFile = () => {
  voiceRefs.value.open()
}
const callListRefs = ref(null)
/*新增名单*/
const addCall = () => {
  callListRefs.value.open('create')
}
const voiceListRefs = ref(null)
/*新增语音文件*/
const addVoice = () => {
  voiceListRefs.value.open('create')
}
const formRef = ref() // 表单 Ref

const taskId = ref('')

const qualityOption = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  taskId.value = false
  dialogTitle.value = t('action.' + type)
  formType.value = type
  selectCallName.value = undefined
  selectVoiceName.value = undefined
  outNumberList.value = await CmOutnumberApi.getCmOutnumberTenantList()
  ttsTimbreOption.value = await TaskApi.ttsTimbre()
  groupOptions.value = await AgentApi.groupSimple()
  ivrOptions.value = await getIvrGroupList()
  qualityOption.value = await getQualitySimpleList()
  resetForm()
  // 修改时，设置数据
  if (id) {
    taskId.value = id
    formLoading.value = true
    try {
      formData.value = await TaskApi.getTask(id)
      selectCallName.value = formData.value.groupName
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const symbolMap = {
  10: '*',
  11: '#'
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formType.value === 'create' && !formData.value.callTaskCalleeListId) {
    ElMessage.warning('请选择呼叫名单')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    for (const keys in data) {
      if (data[keys] == null) delete data[keys]
    }
    if (formType.value === 'create') {
      await TaskApi.createTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await TaskApi.updateTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/*选择名单*/
const changeCalle = (val) => {
  selectCallName.value = val.name
  formData.value.callTaskCalleeListId = val.id
}
/*选择录音文件*/
const changeVoice = (val) => {
  selectVoiceName.value = val.name
  formData.value.audioFile = val.remoteId
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    audioFile: undefined,
    maxNum: 1,
    autoRecall: 1,
    recallTime: 1,
    dialInterval: 1,
    callTaskCalleeListId: undefined,

    startTime1: undefined,
    endTime1: undefined,

    startTime2: undefined,
    endTime2: undefined,

    startTime3: undefined,
    endTime3: undefined,

    ivrFlowId: ''
  }
  formRef.value?.resetFields()
}
</script>
<style scoped lang="scss">
.week-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .time-box {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: calc(100% - 220px);
  }
}

.call-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  .call-select {
    width: calc(100% - 80px);
    padding-left: 10px;
    margin-right: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .call-holder {
    width: calc(100% - 80px);
    padding-left: 10px;
    margin-right: 5px;
    color: #a8abb2;
  }

  .icon-box {
    width: 40px;
    height: 32px;
    background: #f7f7f7;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
</style>
